import MqttDevice from "./MqttDevice";
import {TopicFunction} from "./TopicFactory";


export default class ClientDevice extends MqttDevice {
  constructor(clientDataListener, deviceBasicData, deviceModel) {
    super(deviceBasicData, deviceModel);
    this.clientDataListener = clientDataListener;
    this.setDataListener(this);
  }

  onConnect(sucess){
    !!this.clientDataListener.onConnect && this.clientDataListener.onConnect(sucess);
  }

  onSubAck(sucess){
    !!this.clientDataListener.onSubAck && this.clientDataListener.onSubAck(sucess);
  }

  onPushAck(sucess){
    !!this.clientDataListener.onPushAck && this.clientDataListener.onPushAck(sucess);
  }
  onClose(sucess){
    !!this.clientDataListener.onClose && this.clientDataListener.onClose(sucess);
  }

  onHandle(topic, msg){
    !!this.clientDataListener.onHandle && this.clientDataListener.onHandle(topic, msg);
  }

  onRequestSuccess(topic, requestPayload) {
    // console.log("onSuccess Request:", JSON.stringify(requestPayload));
    !!this.clientDataListener.onRequestSuccess && this.clientDataListener.onRequestSuccess(topic, requestPayload);

    let topicInfo = this.topicFactory.findThingTopic(topic);
    if (!!topicInfo){
      const fun = topicInfo.fun;
      if (fun == TopicFunction.PropertySet){
        if (requestPayload.getMethod() === "thing.service.property.set") {
          this.clientDataListener.onSetProperty(requestPayload);
        }
      }else if (fun == TopicFunction.Service){
        console.log("Received service call:", JSON.stringify(requestPayload));
        this.clientDataListener.onInvokeService(topic, requestPayload);
      }
    }
  }

  onResponseSuccess(topic, responsePayload) {
    // console.log("onSuccess Request:", JSON.stringify(responsePayload));
    !!this.clientDataListener.onResponseSuccess && this.clientDataListener.onResponseSuccess(topic, responsePayload);

    let topicInfo = this.topicFactory.findThingTopic(topic);
    if (!!topicInfo){
      const fun = topicInfo.fun;
      if (fun == TopicFunction.PropertyPost){
        this.clientDataListener.onResPushProperty(responsePayload);
      }else if (fun == TopicFunction.EventPost){
        this.clientDataListener.onResPushEvent(responsePayload);
      }
    }
  }

  onError(code, msg) {
    this.clientDataListener.onError(code, msg);
  }
}

